//
//  LXNetworkTool.swift
//  LXTXShop
//
//  Created by apple on 2018/4/10.
//  Copyright © 2018年 LX. All rights reserved.
//

import UIKit
import Alamofire
import SwiftyJSON
import CryptoSwift

class LXNetworkTool: NSObject {
    func requestUrl(_ url: String, params: Dictionary <String, String>?,success:@escaping ((JSON)->()),failure:@escaping ((String)->()) ){
        
        let urlx = BASEREQUESTURL+url;
        
        let i = Int(Date().timeIntervalSince1970)
        let p:Dictionary = ["t":String(i),"client":"ios","version":VERSION]
        
        let mp = NSMutableDictionary(dictionary: p)
        if params?.isEmpty==nil { }else{
            mp.addEntries(from: params!)
        }
        
        let keys:NSMutableArray=NSMutableArray()
        keys.addObjects(from: mp.allKeys)
        keys.sort (comparator: { (obj1, obj2) -> ComparisonResult in
            let str1=obj1 as! String
            let str2=obj2 as! String
            if str1<str2{
                return ComparisonResult.orderedAscending
            }else{
                return ComparisonResult.orderedDescending
            }
        })
        var str = ENCRYPTIONKEY
        for k in keys {
            let v:String = mp[String(describing: k)] as! String
            str += (String(describing: k)+v)
        }
        str+=ENCRYPTIONKEY
        
        let res = str.data(using: String.Encoding.utf8)!.base64EncodedString(options: NSData.Base64EncodingOptions.endLineWithLineFeed)
        
        mp.addEntries(from: ["token":res.md5()]);
        
        print("-----------------------------begin------------------------------------\n")
        print("POST : " + urlx)
        var index = 0
        for (k,v) in mp{
            index += 1
            print("PARAM \(index) :  \(k) -> \(v)")
        }
        print("\n------------------------------end-------------------------------------\n")
        
        var mpp:Dictionary<String,String> = [String : String]()
        
        for (k,v) in mp {
            mpp[k as! String] = v as? String
        }
        
        let requests = Alamofire.request(urlx,method: .post, parameters: mpp, encoding: URLEncoding.default, headers: nil)
        
        requests.responseJSON(completionHandler: { (res) in
            
            guard res.result.isSuccess else{
                let error = res.result.error?.localizedDescription
                print("-----------------------------begin------------------------------------\n")
                print("failure:" + urlx , res.result.error ?? "未知错误" , res.result)
                print("\n------------------------------end-------------------------------------\n")
                failure(error!)
                return
            }
            if res.result.value != nil {
                if let v = res.result.value{
                    print("-----------------------------begin------------------------------------\n")
                    let json = JSON(v)
                    print(urlx,"\n",json)
                    success(json)
                    print("\n------------------------------end-------------------------------------\n")
                }
            }
        })
    }
    
    //MARK: - 照片上传
    ///
    /// - Parameters:
    ///   - urlString: 服务器地址
    ///   - params: ["key":""] - key 为必传参数
    ///   - data: image转换成Data
    ///   - name: fileName
    ///   - success:
    ///   - failture:
    func upLoadImage(urlString : String, params:Dictionary< String, String>?, data: [Data]?,success : @escaping (_ response : (JSON))->(), failture : @escaping (_ error : Error)->()){
        let urlx = BASEREQUESTURL+urlString;
        let headers = ["content-type":"multipart/form-data"]
        
        let i = Int(Date().timeIntervalSince1970)
        let p:Dictionary = ["t":String(i),"client":"ios","version":VERSION]
        let mp = NSMutableDictionary(dictionary: p)
        if params?.isEmpty==nil { }else{
            mp.addEntries(from: params!)
        }
        
        let keys:NSMutableArray=NSMutableArray()
        keys.addObjects(from: mp.allKeys)
        keys.sort (comparator: { (obj1, obj2) -> ComparisonResult in
            let str1=obj1 as! String
            let str2=obj2 as! String
            if str1<str2{
                return ComparisonResult.orderedAscending
            }else{
                return ComparisonResult.orderedDescending
            }
        })
        var str = ENCRYPTIONKEY
        for k in keys {
            let v:String = mp[String(describing: k)] as! String
            str += (String(describing: k)+v)
        }
        str+=ENCRYPTIONKEY
        
        let res = str.data(using: String.Encoding.utf8)!.base64EncodedString(options: NSData.Base64EncodingOptions.endLineWithLineFeed)
        
        mp.addEntries(from: ["token":res.md5()]);
        
        print("-----------------------------begin------------------------------------\n")
        print("POST : " + urlx)
        var index = 0
        for (k,v) in mp{
            index += 1
            print("PARAM \(index) :  \(k) -> \(v)")
        }
        print("\n------------------------------end-------------------------------------\n")
        
        Alamofire.upload(
            multipartFormData: { multipartFormData in
                for (k,v) in mp{
                    multipartFormData.append( (String(describing: v).data(using: String.Encoding.utf8)!), withName: String(describing: k))
                }
                
                for i in 0..<data!.count {
                    let imageName = String(describing: NSDate()) + "\(i).png"
                    multipartFormData.append(data![i], withName: "image_data", fileName: imageName, mimeType: "image/png")
                }
        },
            to: urlx,
            headers: headers,
            encodingCompletion: { encodingResult in
                switch encodingResult {
                case .success(let upload, _, _):
                    upload.responseJSON { response in
                        if let value = response.result.value as? [String: AnyObject]{
                            let json = JSON(value)
                            success(json)
                        }
                    }
                case .failure(let encodingError):
                    failture(encodingError)
                }
        }
        )
    }
}
